import { message } from '@tauri-apps/api/dialog';
import { WebviewWindow, getAll } from '@tauri-apps/api/window';
export const windowConfig = {
  label: '',
  title: '',
  url: '',
  width: 500,
  height: 400,
  minWidth: 200,
  minHeight: 200,
  center: true,
  maximized: false,
};

class WindowManager {
  public mainWin = null;
  constructor() {
    this.mainWin = null;
  }
  // 获取窗口
  getWin(label: string) {
    return WebviewWindow.getByLabel(label);
  }
  // 获取所有窗口
  getAllWin() {
    return getAll();
  }

  // 判断窗口是否已存在
  isExsitWin(label: string) {
    return !!getAll().find((w) => w.label === label);
  }
  // 创建新窗口
  async createWin(
    options: Partial<typeof windowConfig>,
    { onCreated, onError }: { onCreated?: any; onError?: any } = {},
  ) {
    const args = Object.assign({}, windowConfig, options);
    //   判断窗口是否存在
    const exsitWin = getAll().find((w) => w.label === args.label);
    if (exsitWin) {
      if (!exsitWin.label.includes('main')) {
        await exsitWin.unminimize();
        await exsitWin.setFocus();
        return;
      }
      await exsitWin.close();
    }
    const { label, ...params } = args;
    let win = new WebviewWindow(label, params);
    win.once('tauri://created', onCreated);
    win.once('tauri://destroy', () => {
      console.log('destroy');
    });
    win.once('tauri://error', async () => {
      await message('窗口创建失败', '错误提示');
      onError && onError();
    });
  }

  async closeWin(label: string) {
    const win = this.getWin(label);
    if (win) {
      win.close();
    }
  }
}

export default new WindowManager();
